package org.fms.web.controller;

import com.alibaba.fastjson.JSON;
import org.fms.web.service.LoginService;
import org.fms.web.service.OperatorService;
import org.fms.web.service.vo.AnnexVO;
import org.fms.web.service.vo.PageResultVO;
import org.fms.web.service.vo.RegistrationVO;
import org.fms.web.service.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;


/**
 * PACKAGE     : org.fms.web.controller
 * CREATE DATE : 2018-03-03
 * AUTHOR      : xiaolu.fan
 * 文件描述     :Rest API
 */
@Controller
public class IndexController {

    private Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    private OperatorService operatorService;

    @Autowired
    private LoginService loginService;

    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("/login")
    public String login() {
        Map map1 = operatorService.getBasicInfo(1);
        logger.error(map1 == null ? null : map1.toString());
        return "login";
    }

    @RequestMapping(value = "/createNewDoc", method = RequestMethod.GET)
    public String createNewPage() {
        return "newPage";
    }

    @RequestMapping(value = "/newPage", method = RequestMethod.POST)
    @ResponseBody
    public String newPage(ModelMap modelMap) {
        logger.error("/newPage...");
        modelMap.addAttribute("msg", "graceful!");
        String json = JSON.toJSONString(modelMap);
        return json;
    }

    @RequestMapping(value = "/newCreate", method = RequestMethod.POST)
    @ResponseBody
    public String newCreatePage(RegistrationVO registrationVO) {
        ModelMap modelMap = new ModelMap();
        logger.error(modelMap.toString());
        logger.error(registrationVO.toString());
        Integer intKey = operatorService.saveRegistration(registrationVO);
        logger.error("" + intKey);
        modelMap.addAttribute("status", 0);
        return JSON.toJSONString(modelMap);
    }

    @RequestMapping(value = "login/index", method = RequestMethod.GET)
    @ResponseBody
    public String index(Integer pageNumber, Integer pageSize) {
        logger.error("pageNumber:" + pageNumber);
        logger.error("pageSize:" + pageSize);
        PageResultVO pageResultVO = operatorService.getAllByPageList(pageNumber, pageSize);
        logger.error(pageResultVO == null ? null : pageResultVO.toString());
        return JSON.toJSONString(pageResultVO);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public String save(RegistrationVO registrationVO){
        ModelMap modelMap = new ModelMap();
        Integer intKey = operatorService.save(registrationVO);
        logger.error("" + intKey);
        modelMap.addAttribute("status", 0);
        return JSON.toJSONString(modelMap);
    }
    /**
     * 删除操作
     * @param id
     * @return
     */
    @RequestMapping(value = "delete",method = RequestMethod.GET)
    @ResponseBody
    public Integer delete(Integer id){
        return operatorService.delete(id);
    }


    @RequestMapping(value = "getDetailData", method = RequestMethod.GET)
    @ResponseBody
    public String getDetailData(Integer id) {
        RegistrationVO registrationVO = operatorService.getDetailData(id);
        if (registrationVO == null) {
            return null;
        }
        return JSON.toJSONString(registrationVO);
    }

    @RequestMapping(value = "index/detail", method = RequestMethod.GET)
    public String detailPage(Integer id) {
        return "detail";
    }


    /**
     * 插入操作
     *
     * @param registrationVO
     */
    @RequestMapping(value = "login/insertRegistration", method = RequestMethod.POST)
    @ResponseBody
    public void insertRegistration(@RequestBody RegistrationVO registrationVO) {
        operatorService.saveRegistration(registrationVO);
    }

    @RequestMapping(value = "login/insertAnnex", method = RequestMethod.POST)
    @ResponseBody
    public void insertAnnex(@RequestBody AnnexVO annexVO) {
        logger.error(annexVO.getRegistrationId() + " , " + annexVO.getUrl());
        operatorService.saveAnnex(annexVO);
    }

    @RequestMapping(value = "login/insertUser", method = RequestMethod.POST)
    @ResponseBody
    public String insertUser(@RequestBody UserVO userVO) {
        UserVO userVO1 = new UserVO();
        logger.error("username=" + userVO.getUsername() + " , password=" + userVO.getPassword());
        return "123124";
    }

    @RequestMapping(value = "/upload/avatarUrl", method = RequestMethod.POST)
    public @ResponseBody
    String uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        String filePath = request.getSession().getServletContext().getRealPath("upload/images/");
        try {
            uploadFile(file.getBytes(), filePath, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("fileName", fileName);
        modelMap.addAttribute("filePath", "/upload/images/");
        return JSON.toJSONString(modelMap);
    }

    /**
     * 上传附件
     */
    @RequestMapping(value = "/upload/enclosure", method = RequestMethod.POST)
    public @ResponseBody
    String uploadEnclosure(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        String filePath = request.getSession().getServletContext().getRealPath("upload/enclosures/");
        try {
            uploadFile(file.getBytes(), filePath, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("fileName", fileName);
        modelMap.addAttribute("filePath", "/upload/enclosures/");
        return JSON.toJSONString(modelMap);
    }

    /**
     * 工具类
     *
     * @param file
     * @param filePath
     * @param fileName
     * @throws Exception
     */
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }
}